package com.zhiyou100.api.io_demo;



import java.io.*;
import java.time.LocalDate;

/**
 * 对象流（字节）：
 *  ObjectInputStream：  读取    反序列化
 *  ObjectOutputStream：  写入   持久化（对象持久化需要实现序列化接口）
 */
public class Demo5 {


    public static void main(String[] args) throws IOException, ClassNotFoundException {
//        testWriter();
//        testRead();
        testPrint();
    }

    //持久化一个图书对象到bookInfo.txt
    public static void testWriter() throws IOException {
        File targetFile = new File("./java_api/bookInfo.txt");
        FileOutputStream fos = new FileOutputStream(targetFile);
        //基于字节流创建一个对象字节流
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        BookInfo bookInfo = new BookInfo("1001","动物世界",80,"张三", LocalDate.now());
        BookInfo bookInfo2 = new BookInfo("1002","动物世界",80,"张三", LocalDate.now());
        BookInfo bookInfo3 = new BookInfo("1003","动物世界",80,"张三", LocalDate.now());
        oos.writeObject(bookInfo);
        oos.writeObject(bookInfo2);
        oos.writeObject(bookInfo3);
//        oos.writeObject(null);
        oos.flush();
    }

    //将持久化对象反序列化
    public static void testRead() throws IOException, ClassNotFoundException {
        File targetFile = new File("./java_api/bookInfo.txt");
        InputStream is = new FileInputStream(targetFile);
        ObjectInputStream ois = new ObjectInputStream(is);
        Object o = ois.readObject();
        try {
            while(o != null){
                if (o instanceof BookInfo){
                    System.out.println((BookInfo) o);
                }
                o = ois.readObject();
            }
        }catch (EOFException e){
            System.out.println("end......");
        }
    }
    //打印流
    public static void testPrint() throws IOException {
        File targetFile = new File("./java_api/file2.txt");
        PrintWriter pw = new PrintWriter(targetFile);
        pw.write("好好学习，天天向上");
        pw.flush();

    }


}
